﻿using Shape.Mvp;
using Shape.Mvp.Presenters;
using SimpleTasks.Domain.Model;
using SimpleTasks.Domain.Repositories;
using SimpleTasks.Events;
using SimpleTasks.Persistence;
using SimpleTasks.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleTasks.Presenters
{
   public class SimpleTaskItemPresenter : Presenter<ISimpleTaskItemView>
   {
      private IUnitOfWork _currentUnitOfWork;
      private IRepository<SimpleTask> _simpleTaskRepository;

      public SimpleTaskItemPresenter(IApplicationController applicationController,
                                     IUnitOfWork unitOfWork, 
                                     IRepository<SimpleTask> simpleTaskRepository, 
                                     ISimpleTaskItemView view) : base(applicationController, view)
      {
         _currentUnitOfWork = unitOfWork;
         _simpleTaskRepository = simpleTaskRepository;
      }

      public void Initialise()
      {
         View.Create += OnViewCreate;
      }

      public void OnViewCreate()
      {
         if (!String.IsNullOrWhiteSpace(View.Description))
         {
            _currentUnitOfWork.Resume();

            try
            {
               var newSimpleTask = new SimpleTask(View.Description);

               _simpleTaskRepository.Save(newSimpleTask);
               
               _currentUnitOfWork.FlushAndPause();

               View.Description = String.Empty;

               ApplicationController.Publish<SimpleTaskCreatedEvent>(new SimpleTaskCreatedEvent(newSimpleTask.Id));
            }
            catch (Exception)
            {
               _currentUnitOfWork.Abort();
               throw;
            }
            
         }
      }
   }
}
